package com.example.xuanmei.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.xuanmei.data.api.ApiClient
import com.example.xuanmei.data.model.Video
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class VideoViewModel : ViewModel() {
    private val _videos = MutableStateFlow<List<Video>>(emptyList())
    val videos: StateFlow<List<Video>> = _videos.asStateFlow()
    
    private val _loading = MutableStateFlow(false)
    val loading: StateFlow<Boolean> = _loading.asStateFlow()
    
    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error.asStateFlow()
    
    private var currentPage = 0
    private val pageSize = 10
    
    fun loadVideos() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                _loading.value = true
                _error.value = null
                
                val response = ApiClient.apiService.getVideoList(currentPage, pageSize)
                
                response.execute().body()?.let { apiResponse ->
                    if (apiResponse.code == 200) {
                        val newVideos = apiResponse.data ?: emptyList()
                        _videos.value = _videos.value + newVideos
                        currentPage++
                    } else {
                        _error.value = apiResponse.message
                    }
                } ?: run {
                    _error.value = "网络请求失败"
                }
            } catch (e: Exception) {
                _error.value = e.message ?: "未知错误"
            } finally {
                _loading.value = false
            }
        }
    }
    
    fun refreshVideos() {
        currentPage = 0
        _videos.value = emptyList()
        loadVideos()
    }
    
    fun likeVideo(videoId: Long) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                ApiClient.apiService.likeVideo(videoId).execute()
                // 刷新视频列表以获取更新后的点赞数
                refreshVideos()
            } catch (e: Exception) {
                _error.value = e.message ?: "点赞失败"
            }
        }
    }
}
